export class Version {
    static fromString(version) {
        const versionParts = version
            .split(/[.-]/)
            .map(part => parseInt(part) || 0);
        return Version.from(...versionParts);
    }

    static from(major, minor, patch) {
        if (typeof major === "string") {
            return Version.fromString(major);
        }
        return new Version(major, minor, patch);
    }

    major = 0;
    minor = 0;
    patch = 0;
    version;

    constructor(major, minor, patch = 0) {
        this.major = parseInt(major, 10) || 0;
        this.minor = parseInt(minor, 10) || 0;
        this.patch = parseInt(patch, 10) || 0;
        this.version = [this.major, this.minor, this.patch].join(".");
    }

    equals(ver) {
        return this.major === ver.major
            && this.minor === ver.minor
            && this.patch === ver.patch;
    }

    lessThen(ver) {
        const compare = (a, b) => a === b ? null : a < b;
        const predicates = "major.minor.patch".split(".")
            .map(key => () => compare(this[key], ver[key]));
        for (var predicate of predicates) {
            const r = predicate();
            if (r === null) { continue; }
            return r;
        }
    }

    gratherThen(ver) {
        return ver.lessThen(this);
    }

    between(ver1, ver2) {
        return (this.equals(ver1) || this.gratherThen(ver1)) && this.lessThen(ver2);
    }
}

export default async function () {
    const res = await fetch("./package.json");
    const json = await res.json();
    if (!json) { return "" };
    const { version } = json;

    return Version.from(version);
}
